package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceimpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
       //select sum(amount) from orders where order_time between ? and ? group by date
        //取出日期集合
        List<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);
        //循环到结束日期
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            datelist.add(begin);
        }
        //根据日期获得当天营业额集合
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : datelist){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //将查询字段封装到map集合中
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            //判断营业额是否为空
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        //返回结果 将集合转换为字符串
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(datelist,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
       List<LocalDate> dateList = new ArrayList<>();
       dateList.add(begin);
       while (!begin.equals(end)){
           begin = begin.plusDays(1);
           dateList.add(begin);
       }
       //用户数据获取
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
           LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
           LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
               //调用方法查询用户数据
            //select count(id) from orders where create_time > ? and create_time < ?
                Integer  newUser= getUserStatistics(beginTime, endTime);
                 newUserList.add(newUser);
            //select count(id) from orders where   create_time < ?
                Integer  totalUser = getUserStatistics(null, endTime);
                 totalUserList.add(totalUser);

       }
        //返回结果，集合转换为字符串封装到vo中
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 订单数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //订单数据获取
        List<Integer> validOrderCountList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer validOrderCount = countOrderStatus(beginTime, endTime, Orders.COMPLETED);
            Integer orderCount = countOrderStatus(beginTime, endTime, null);
            validOrderCountList.add(validOrderCount);
            orderCountList.add(orderCount);
        }
        //订单总数、有效订单数、订单完成率
        Integer totalvalidOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = totalvalidOrderCount.doubleValue() / totalOrderCount;
        }
        //返回结果
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalvalidOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    /**
     * 销量排名统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime,endTime);
        //获取商品名称和数量
        String name = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String number = StringUtils.join(goodsSalesDTOList.stream().map(item -> item.getNumber().toString()).collect(Collectors.toList()), ",");
        return SalesTop10ReportVO.builder()
                .nameList(name)
                .numberList(number)
                .build();


    }

    /**
     * 导出Excel
     *
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate beginDay = LocalDate.now().minusDays(30);
        LocalDate endDay = LocalDate.now().plusDays(1);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(beginDay, LocalTime.MIN), LocalDateTime.of(endDay, LocalTime.MIN));
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook Excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = Excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间：" + beginDay + "至" + endDay);
            //获取单元格  4-5行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //准备明细数据
            for (int i = 0; i <30; i++) {
                LocalDate date = beginDay.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //浏览器下载
            ServletOutputStream outputStream = response.getOutputStream();
            Excel.write(outputStream);
            //释放资源
            outputStream.close();
            Excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


/////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 获取用户统计数据
     *
     * @param begin
     * @param end
     * @return
     *
     */
    private Integer getUserStatistics(LocalDateTime begin, LocalDateTime end) {
        Map map = new HashMap<>();
        map.put("end",end);
        map.put("begin",begin);
        return userMapper.countByMap(map);

    }
    /**
     * 根据时间区间统计指定状态的订单数量
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Integer countOrderStatus(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap<>();
        map.put("begin",beginTime);
        map.put("end",endTime);
        map.put("status",status);
        return orderMapper.countByMap(map);
    }
}
